package me.yidasanqian.crowdfunding.app;

import me.yidasanqian.crowdfunding.domain.Media;
import me.yidasanqian.crowdfunding.domain.User;
import me.yidasanqian.crowdfunding.service.IJwtService;
import me.yidasanqian.crowdfunding.service.IMediaService;
import me.yidasanqian.crowdfunding.service.IUserService;
import me.yidasanqian.crowdfunding.util.JwtUtils;
import me.yidasanqian.crowdfunding.vo.ResultModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Linyu Chen
 */
@RestController
@RequestMapping("api/v1/user")
public class UserApi {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private IUserService userService;

    @Resource
    private IJwtService jwtService;

    @Resource
    private IMediaService mediaService;

    @Value("${spring.http.multipart.location}")
    private String filePath;

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public Object logout(@RequestParam("userId") Long userId, @RequestParam("token") String token) {
        boolean isExp = JwtUtils.expirationJwt(token);
        if (isExp) {
            jwtService.deleteByUserId(userId);
            return ResultModel.success();
        } else {
            return ResultModel.fail(1006, "退出异常");
        }
    }

    @RequestMapping(value = "uploadAvatar", method = RequestMethod.POST)
    public Object uploadAvatar(@RequestParam("userId") Long userId,
                               @RequestParam("file") MultipartFile file,
                               HttpServletRequest request) {

        if (file.isEmpty()) {
            return ResultModel.fail(1007, "上传的文件不能为空");
        }

        String avatarUrl = null;
        try {
            // 判断文件类型
            if (!file.getContentType().contains("image/")) {
                return ResultModel.fail(1012, "不允许的媒体文件类型");
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("上传的后缀名为：" + suffixName);

            // 解决中文问题，liunx下中文路径，图片显示问题
            fileName = UUID.randomUUID() + suffixName;
            String fileUri = "image/" + fileName;
            String pathName = filePath + fileUri;
            File dest = new File(pathName);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);

            String servletPath = request.getScheme() + "://" + request.getServerName() +
                    ":"+ request.getServerPort();
            log.debug("当前项目servletPath路径 ==》" + servletPath);
            avatarUrl = fileUri;

            User user = userService.selectByPrimaryKey(userId);
            Long mediaId = user.getMedia().getId();
            Media media = mediaService.selectByPrimaryKey(mediaId);
            if (media == null) {
                media = new Media();
                media.setTitle("用户头像");
                //media.setCreatetime(new Date());
                media.setMediaType(0);
                media.setUrl(avatarUrl);
                mediaService.save(media);
            } else {
                //media.setUpdatetime(new Date());
                media.setUrl(avatarUrl);
            }

            user.setMedia(media);
            userService.update(user);

        } catch (IOException e) {
            log.error(e.getMessage(),e);
            ResultModel.error(5000, "服务器异常");
        }

        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("avatarUrl", avatarUrl);
        return ResultModel.success(map);
    }

    @RequestMapping(value = "updateUser", method = RequestMethod.POST)
    public Object updateUser(@RequestParam("userId") Long userId,
                             @RequestParam(value = "nickname", required = false) String nickname,
                             @RequestParam(value = "sex", required = false) Integer sex,
                             @RequestParam(value = "idCard", required = false)String idCard,
                             @RequestParam(value = "name", required = false)String name) {
        User user = userService.selectByPrimaryKey(userId);
        if (user == null) {
            return ResultModel.fail(1009, "用户不存在");
        } else {
            if (StringUtils.isEmpty(nickname) && sex == null && StringUtils.isEmpty(idCard)
                    && StringUtils.isEmpty(name)) {
                return ResultModel.fail(1010, "参数非法");
            }
        }

        if (!StringUtils.isEmpty(nickname)) {
            user.setNickname(nickname);
        }
        if (sex != null) {
            user.setSex(sex);
        }
        if (!StringUtils.isEmpty(idCard)) {
            user.setIdentityCard(idCard);
        }
        if (!StringUtils.isEmpty(name)) {
            user.setName(name);
        }
        //user.setUpdatetime(new Date());
        userService.update(user);
        return ResultModel.success();
    }


    @RequestMapping(value = "getUserInfo", method = RequestMethod.GET)
    public Object getUserInfo(@RequestParam("userId") Long userId) {
        User user = userService.selectByPrimaryKey(userId);
        return ResultModel.success(user);
    }
}
